package com.woniu108.product.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.carService.commos.dto.*;
import com.woniu108.carService.commos.exception.admin.AdminException;
import com.woniu108.carService.commos.exception.admin.AdminExceptionCode;
import com.woniu108.carService.commos.exception.produnt.ProductException;
import com.woniu108.carService.commos.util.StaticData;
import com.woniu108.product.client.PersonClient;
import com.woniu108.product.mapper.PreOrderMapper;
import com.woniu108.product.mapper.ServiceInfoMapper;
import com.woniu108.product.model.PreOrder;
import com.woniu108.product.model.ServiceInfo;
import com.woniu108.product.param.*;
import com.woniu108.product.service.PreOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务预约表 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class PreOrderServiceImpl extends ServiceImpl<PreOrderMapper, PreOrder> implements PreOrderService {
    @Resource
    private PreOrderMapper preOrderMapper;
    @Resource
    private PersonClient personClient;
    @Resource
    private ServiceInfoServiceImpl serviceInfoServiceImpl;
    @Resource
    private ServiceInfoMapper serviceInfoMapper;

    /**
     * 判断店家
     */
    private Integer isStore(String storeAdminId) {
        // 检查 adminId 是否为 null
        if (storeAdminId == null) {
            throw new AdminException(AdminExceptionCode.STORE_ADMIN_ID_NULL);
        }
        // 判断店家权限
        StoreAdminDto dto = personClient.getStoreAdminInfoById(storeAdminId).getData();
        if (dto == null) {
            throw new AdminException(AdminExceptionCode.STORE_ADMIN_NOT_HAVE);
        }
        if (!Objects.equals(dto.getStoreAdminState(), StaticData.ADMIN_STATE_NORMAL)) {
            throw new AdminException(AdminExceptionCode.STORE_ADMIN_STATE_ERROR);
        }
        return dto.getStoreId();
    }

    /**
     * 判断用户
     */
    private void isUser(String userId) {
        // 检查 userId 是否为 null
        if (userId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断用户
        UserInfoDto userInfo = personClient.getByUserId(userId).getData();
        if (userInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
    }

    /**
     * 将字符串中的ID取出放入集合
     */
    public static List<Integer> stringToNumber(String preInfoIds) {
        List<Integer> numbers = new ArrayList<>();

        // 使用逗号分隔字符串
        String[] numberStrings = preInfoIds.split(",");

        // 遍历每个子字符串并转换为整数
        for (String numberStr : numberStrings) {
            try {
                // 将字符串转换为整数并添加到集合中
                numbers.add(Integer.parseInt(numberStr));
            } catch (NumberFormatException e) {
                // 处理可能的格式异常
                e.printStackTrace();
            }
        }

        return numbers;
    }

    /**
     * 将集合中的ID变成字符串
     */
    public static String numberListToString(List<Integer> numbers) {
        return numbers.stream()
                // 将每个数字转换为字符串
                .map(String::valueOf)
                // 将字符串用逗号分隔并拼接
                .collect(Collectors.joining(","));
    }

    private List<PreOrderDto> preOrderToDto(List<PreOrder> orders) {
        //设dto集合
        ArrayList<PreOrderDto> dtos = new ArrayList<>();
        for (PreOrder order : orders) {
            //复制信息
            PreOrderDto dto = BeanUtil.toBean(order, PreOrderDto.class);
            //查用户信息
            UserInfoDto userId = personClient.getByUserId(order.getUserId()).getData();
            dto.setUserNickName(userId.getUserNickName());
            dto.setUserPhone(userId.getUserPhone());
            //查门店信息
            StoreDto storeById = personClient.getStoreById(order.getStoreId()).getData();
            dto.setStoreName(storeById.getStoreName());
            dto.setStoreAddress(storeById.getStoreAddress());
            //查服务信息
            List<Integer> integers = stringToNumber(order.getServiceIds());
            ArrayList<ServiceInfoDto> infoDtos = new ArrayList<>();
            for (Integer serviceId : integers) {
                ServiceInfoDto serviceInfoDto = serviceInfoServiceImpl.findServiceInfoById(serviceId);
                infoDtos.add(serviceInfoDto);
            }
            dto.setServiceInfoDtos(infoDtos);

        }
        return dtos;
    }

    @Override
    public List<PreOrderDto> findStorePreOrder(String storeAdminId) {
        //判断门店,获取门店id
        Integer storeId = isStore(storeAdminId);
        //查询待处理预约
        QueryWrapper<PreOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("store_id", storeId).eq("pre_order_state", StaticData.PRE_ORDER_STATE_PENDING)
                .eq("pre_order_state", StaticData.PRE_ORDER_STATE_AGREE);
        List<PreOrder> orders = preOrderMapper.selectList(wrapper);

        return preOrderToDto(orders);
    }

    @Override
    public List<PreOrderDto> findAllUserPreOrder(String userId) {
        //判断用户id
        isUser(userId);
        //查询用户全部预约
        QueryWrapper<PreOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .orderByAsc("pro_order_state");
        List<PreOrder> orders = preOrderMapper.selectList(wrapper);
        return preOrderToDto(orders);
    }

    @Override
    public Boolean storeAgreePreOrder(StoreAgreePreOrderParam param) {
        //判断门店,获取门店id
        Integer storeId = isStore(param.getStoreAdminId());
        //查预约
        PreOrder order = preOrderMapper.selectById(param.getPreOrderId());
        if (order == null) {
            throw new ProductException(500, "该预约不存在");
        }
        if (!Objects.equals(storeId, order.getStoreId())) {
            throw new ProductException(500, "不是你门店的预约");
        }
        if (!Objects.equals(order.getPreOrderState(), StaticData.PRE_ORDER_STATE_PENDING)) {
            throw new ProductException(500, "该预约已被处理");
        }
        order.setPreOrderState(StaticData.PRE_ORDER_STATE_AGREE);
        int update = preOrderMapper.updateById(order);
        return update > 0;
    }

    @Override
    public Boolean storeDisAgreePreOrder(StoreAgreePreOrderParam param) {
        //判断门店,获取门店id
        Integer storeId = isStore(param.getStoreAdminId());
        //查预约
        PreOrder order = preOrderMapper.selectById(param.getPreOrderId());
        if (order == null) {
            throw new ProductException(500, "该预约不存在");
        }
        if (!storeId.equals(order.getStoreId())) {
            throw new ProductException(500, "不是你门店的预约");
        }

        if (!Objects.equals(order.getPreOrderState(), StaticData.PRE_ORDER_STATE_PENDING)) {
            throw new ProductException(500, "该预约已被处理");
        }
        order.setPreOrderState(StaticData.PRE_ORDER_STATE_DISAGREE);
        int update = preOrderMapper.updateById(order);
        return update > 0;
    }

    @Override
    public Boolean userCancelPreOrder(UserCancelPreOrderParam param) {
        //判断用户
        isUser(param.getUserId());
        //查预约
        PreOrder order = preOrderMapper.selectById(param.getPreOrderId());
        if (order == null) {
            throw new ProductException(500, "该预约不存在");
        }
        if (!Objects.equals(order.getPreOrderState(), StaticData.PRE_ORDER_STATE_PENDING) || !Objects.equals(order.getPreOrderState(), StaticData.PRE_ORDER_STATE_AGREE)) {
            throw new ProductException(500, "该预约已被处理");
        }
        if (!Objects.equals(order.getUserId(), param.getUserId())) {
            throw new ProductException(500, "不是你的预约");
        }
        order.setPreOrderState(StaticData.PRE_ORDER_STATE_USER_CANCEL);
        int update = preOrderMapper.updateById(order);
        return update > 0;
    }

    @Override
    public Boolean finishPreOrder(FinishPreOrderParam param) {
        //判断管理员
        Integer storeId = null;
        if (param.getStoreAdminId() != null) {
            storeId = isStore(param.getStoreAdminId());
        } else {
            isUser(param.getUserId());
        }
        //查预约
        PreOrder order = preOrderMapper.selectById(param.getPreOrderId());
        if (order == null) {
            throw new ProductException(500, "该预约不存在");
        }
        if (storeId != null) {
            if (!Objects.equals(order.getUserId(), param.getUserId())) {
                throw new ProductException(500, "不是你的预约");
            }
        }
        if (param.getUserId() != null) {
            if (!Objects.equals(order.getUserId(), param.getUserId())) {
                throw new ProductException(500, "不是你的预约");
            }
        }
        order.setPreOrderState(StaticData.PRE_ORDER_STATE_HAVE_ARRIVE);
        int update = preOrderMapper.updateById(order);
        return update > 0;
    }

    @Override
    public Boolean userDeletePreOrder(UserDeletePreOrderParam param) {
        //判断用户
        isUser(param.getUserId());
        //查预约
        PreOrder order = preOrderMapper.selectById(param.getPreOrderId());
        if (order == null) {
            throw new ProductException(500, "该预约不存在");
        }
        if (!Objects.equals(order.getUserId(), param.getUserId())) {
            throw new ProductException(500, "不是你的预约");
        }
        if (Objects.equals(order.getPreOrderState(), StaticData.PRE_ORDER_STATE_PENDING) || Objects.equals(order.getPreOrderState(), StaticData.PRE_ORDER_STATE_AGREE)) {
            throw new ProductException(500, "此状态预约无法删除");
        }
        int delete = preOrderMapper.deleteById(param.getPreOrderId());
        return delete > 0;
    }

    @Override
    public Boolean userInsertPreOrder(UserInsertPreOrderParam param) {
        //判断用户
        isUser(param.getUserId());
        //服务id
        String serviceIds = numberListToString(param.getServiceIds());
        //门店id
        ServiceInfo serviceInfo = serviceInfoMapper.selectById(param.getServiceIds().get(0));
        Integer storeId=serviceInfo.getStoreId();
        //预约订单编号
        String preOrderId = new Snowflake(1, 1).nextIdStr();
        PreOrder order = new PreOrder();
        order.setPreOrderId(preOrderId);
        order.setPreOrderTime(LocalDateTime.now());
        order.setUserId(param.getUserId());
        order.setStoreId(storeId);
        order.setPreTime(param.getPreTime());
        order.setServiceIds(serviceIds);
        order.setPreOrderState(StaticData.PRE_ORDER_STATE_PENDING);
        int insert = preOrderMapper.insert(order);
        return insert>0;
    }
}
